import i18n from "basic/i18n";
import Vue from "vue";
import Router from "vue-router";
import {Message} from "element-ui";
import handler from "./handler";
import storeUtils from "utils/StoreUtils";
import {routeNoAuth, routeAuth} from "./routes";

Vue.use(Router);
//生成路由列表
const router = new Router({
	mode: process.env.NODE_ENV === "production" ? "hash" : "history",
	routes: [
		{
			name: "index",
			path: "/",
			redirect: "/login"
		},
		{
			name: "home-page",
			path: "/dashboard",
			component: resolve => require(["components/public/HomePage.vue"], resolve),
			children: routeAuth,
			meta: {
				requireAuth: true,
				title: i18n.t("dashboard"),
				icon: "el-icon-s-home"
			}
		},
		{
			name: "login-page",
			path: "/login",
			component: resolve => require(["components/public/LoginPage.vue"], resolve),
			children: routeNoAuth,
			meta: {
				requireAuth: false,
				title: i18n.t("login"),
				isKeepAlive: true,
				icon: ""
			}
		},
		{
			name: "404",
			path: "*", // 此处需特别注意置于最底部
			redirect: "/404"
		}
	]
});
// 判断该路由是否需要登录权限
router.beforeEach((to, from, next) => {
	handler.init(router);
	// 判断该路由是否需要登录权限
	if (to.meta.requireAuth) {
		// 通过vuex state获取当前的token是否存在
		if (storeUtils.getSessionStore("token")) {
			//处理缓存
			handler.handleCacheData(to, from, next);
		} else {
			Message.error("token获取失败，请检查用户名和密码重新登录!");
			//将跳转的路由path作为参数，登录成功后跳转到该路由
			next({name: "index", params: {redirect: to.fullPath}});
		}
	} else {
		handler.handleCacheData(to, from, next);
	}
});
export default router;
